import { createAsyncThunk } from '@reduxjs/toolkit';
import axios, { AxiosError } from 'axios';
import { API } from '../../helpers/API';
import { RootState } from '..';

interface IBall {
    id: number;
  name: string;
  image: string;
  price: number;
  count: number;
  title: string;
  description: string;
  favorite?: boolean;
}

export const fetchCartSlice = createAsyncThunk<_, IBall, {state: RootState}>(
	'cart/fetchCartSlice',
	async (dataFromCart, thunkAPI) => {
		try {
			const token = thunkAPI.getState().authorization.user.token;
			console.log('token', token);
			const { data } = await axios.post(`${API}/cart`, {
				headers: { 
					Authorization: `Bearer ${token}`
				},
				dataFromCart
			});
			return data;
		} catch (error) {
			if (error instanceof AxiosError) {
				throw new Error(error.response?.data.message);
			}
		}
	}
);